package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.Semaphore;

@Service
@Slf4j
public class SemaphoreExampleService {

    // 初始化信号量，允许同时访问的线程数为 2
    private final Semaphore semaphore = new Semaphore(2);

    public void executeLimitedTask() throws InterruptedException {
        log.info("线程 {} 尝试获取信号量，当前可用许可数量: {}",
                Thread.currentThread().getName(), semaphore.availablePermits());

        // 获取信号量许可
        semaphore.acquire();
        try {
            log.info("线程 {} 成功获取信号量，当前可用许可数量: {}",
                    Thread.currentThread().getName(), semaphore.availablePermits());

            // 模拟受限资源操作
            log.info("线程 {} 正在执行受限任务", Thread.currentThread().getName());
            Thread.sleep(2000);

            log.info("线程 {} 完成任务", Thread.currentThread().getName());
        } finally {
            // 释放信号量许可
            semaphore.release();
            log.info("线程 {} 释放信号量，当前可用许可数量: {}",
                    Thread.currentThread().getName(), semaphore.availablePermits());
        }
    }
}
